<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
    	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
    	<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />
		<title></title>
		<link href="/css/lanai-ui.css" rel="stylesheet" />
		<link rel="stylesheet" href="/plugins/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css">
		<script src="/plugins/vue/vue.min.js"></script>
		
	</head>
	<body>
	<div id="app">
		<section class="content no-padding">
			<div class="box box-widget no-shadow">
				<div class="box-body">
					<div id="toolbar" class="btn-group" style="height: 102px">
			
						<div class="row">
							<div class="col-sm-11">
									<label for="demo-sm">用户名:</label>
									<input type="text" style="width: 200px;height: 34px" class="form-control input-sm" id="usernameId" placeholder="请输入用户名">						
							</div>
							<div class="col-sm-12" style="margin-left: 220px; margin-top: -73px;">
				                	<label for="demo-select">状态</label>
				                	<select class="form-control" id="demo-select" style="width: 100px">
				                		<option value='0'>全部</option>
				                		<option value='1'>正常</option>
				                		<option value='2'>禁用</option>
				                		
				                	</select>
							</div>
						</div>
						<div class="col-sm-12"  >
			
						<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#insertRoleModal" onclick="clearDate()" style="margin-left: -14px"><i class="fa fa-plus"></i>&nbsp;新增</button>
		            	<button type="button" id="queryButton" class="btn btn-primary">查询</button>
		            	<a v-if="hasPermis('sys:man:user:import')"  href="/sys/downExceluser?status=0&">导出用户</a> 
		            	
		            	
		            </div>
		            </div>
					<table id="tb_users"></table>
				</div>
			</div>		
		</section>
	</div>
<div class="myRoleModelOne">			
		<!-- 更改信息（Modal） -->
<div class="modal fade" id="myRoleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					更改信息
				</h4>
			</div>
			<div class="modal-body" >
				  <form action="" method="post">
				      <div class="form-group has-feedback">
				      <input type="text" id="username" class="form-control" disabled="disabled" placeholder="请输入用户名">
				        <span class="fa fa-user form-control-feedback"></span>
				      </div>
				      <div class="form-group has-feedback">
				      <input type="email" id="nickname" class="form-control" placeholder="请输入昵称">
				        <span class="fa fa-smile-o form-control-feedback"></span>
				      </div>
				      <div id="updaterolecheckbox" class="form-group has-feedback">
				      
				      </div>
				      
				      <div class="radio radio-inline radio-success">
				                    <b>状态:</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	                                <input type="radio" name="editradio" id="editstatus1" value="1">
	                                <label for="radio3">
	                                    	正常
	                                </label>
	                  </div>
	                   <div class="radio radio-inline radio-danger">
	                                <input type="radio" name="editradio" id="editstatus2" value="2">
	                                <label for="radio4">
	                                    	禁用
	                                </label>
	                   </div>
				</from>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" id="coloseModel" data-dismiss="modal">关闭</button>
				<button type="button" class="btn btn-primary" onClick="updateUserInfo()">提交</button>
				<input type="hidden" id="editUserId" value="0">
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>
</div>

<div class="myModelOne">		
			<!-- 新增（insertModal） -->
<div class="modal fade" id="insertRoleModal" tabindex="1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					新增
				</h4>
			</div>
			<div class="modal-body" >
				  <form action="" method="post">
				      <div class="form-group has-feedback">
				      <input type="text" id="addusername" class="form-control" placeholder="请输入用户名">
				        <span class="fa fa-user form-control-feedback"></span><span id="addusernamemsg"></span>
				      </div>
				      <div class="form-group has-feedback">
				      <input type="email" id="addnickname" class="form-control" placeholder="请输入昵称">
				        <span class="fa fa-smile-o form-control-feedback"></span>
				      </div>
				  	 <div class="form-group has-feedback">
				      <input type="text" id="adddeptName" onclick="showDeptZtree()" readonly="readonly" class="form-control" placeholder="点击选择">
				        <span class="fa fa-smile-o form-control-feedback"></span>
				      </div>
				      <div id="rolecheckbox" class="form-group has-feedback">
				      
				      </div>
				      <div class="radio radio-inline radio-success">
				                    <b>状态:</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	                                <input type="radio" name="addradio" id="addeditstatus1" value="1">
	                                <label for="radio3">
	                                    	正常
	                                </label>
	                  </div>
	                   <div class="radio radio-inline radio-danger">
	                                <input type="radio" name="addradio" id="addeditstatus2" value="2">
	                                <label for="radio4">
	                                    	禁用
	                                </label>
	                   </div>
				</from>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" id="addcoloseModel" data-dismiss="modal">关闭</button>
				<button type="button" class="btn btn-primary" onClick="insertUser()">提交</button>
				<input type="hidden" id="editUserId" value="0">
				<input type="hidden" id="addeptId" value="0">
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>	
</div>
</div>
<div id="treeDIv">
	
</div>
	</body>
	<script src="/js/jquery.min.js"></script>
	
	<script src="/plugins/layer/layer.js"></script>
	<script type="text/javascript" src="/plugins/ztree/js/jquery.ztree.core.js"></script>
    <script src="/js/lanai-ui.js"></script>
    <script src="/js/comm.js"></script>
    <script>
		new Vue({
			el: '#app',
			data: {
				message: '<h1>菜鸟教程,,,,sss</h1>'
			}
		});
	</script>
    <script type="text/javascript">
$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    
    //3.toolbar
	$("#queryButton").click(function(){
		$('#tb_users').bootstrapTable('refresh', {
				"username":$("#username").val()
			}
		);
		//toastr.info("按钮事件相应");
	})
	
});
    	
 	

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_users').bootstrapTable({
            url: '/sys/userlist',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            queryParamsType:'',
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,     //是否显示刷新按钮
            showFullscreen:false,
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 480,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "userId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            columns: [{
                checkbox: true
            }, {
                field: 'username',
                title: '用户名'
            }, {
                field: 'nickname',
                title: '昵称'
            },
            {
                field: 'deptname',
                title: '所属部门'
            }, {
                field: 'status',
                title: '状态',
                formatter: function(value, row, index){
                	if(value==1){
                		return "正常";
                	}
                	return "<font color='red'>禁用</font>";
                }
            }, {
                field: 'createtime',
                title: '创建时间'
            }, {
                field: 'userId',
                title: '操作',
                formatter: function(value, row, index){
              	  var id = value;
                  var result = "";
                  result += "<a href='javascript:;' class='btn btn-xs blue' data-toggle=\"modal\" data-target=\"#myRoleModal\" onclick=\"editViewById('" + id + "')\" title='编辑'><span class='glyphicon glyphicon-pencil'></span>编辑</a>";
                  result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"DeleteByIds('" + id + "')\" title='删除'><span class='glyphicon glyphicon-remove'></span>删除</a>";
		
                  return result;
                }
            }]
        });
    };


    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        	pageSize: params.pageSize,   //页面大小
            pageNumber: params.pageNumber,  //页码
            username:  $("#usernameId").val(),
            status:$("#demo-select").val()
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};


//select rr.userId,rr.roleId,r.role_name from sys_role r 
//LEFT JOIN sys_user_role rr on r.role_id=rr.roleId
//where rr.userId in(1,11);
function editViewById(userId){
	window.setTimeout(function(){
		loadUserinfo(userId);
	},300);
	
	
}
	
	
function loadUserinfo(userId){
		
		var username= $("#username").val();
		var nickname= $("#nickname").val();
		var status= $("#status").val();
		
		//ajax
		$.ajax({
			type:"post",
			url:"/sys/queryUserById",
			data:{"userId":userId},
			dataType:"json",
			success:function(ret){
				if(ret.code==0){
					//{"code":0,"data":{"userId":12,"username":"等等等","nickname":"等等等","password":"202cb962ac59075b964b07152d234b70","status":2,"createtime":"2019-02-25 21:46:26.0","roleid":null,"rolename":null,"rolecreatetime":null}}
					var result = ret.data;
					$("#username").val(result.username);
					$("#nickname").val(result.nickname);
					$("#editUserId").val(userId);
					if(result.status==1){
						$('input:radio[name=editradio]:nth(0)').attr('checked',true);
					}else{
						$('input:radio[name=editradio]:nth(1)').attr('checked',true);
					}
					
					var roles = ret.rolelist;
					var rolehtml='';
					for(var i=0;i<roles.length;i++){
						if(roles[i].checkeds == 2){
							rolehtml+='<input type="checkbox" name="editRoleId" checked value="'+roles[i].roleid+'" />'+roles[i].rolename+' &nbsp;&nbsp;&nbsp;&nbsp;';
						}else{
							rolehtml+='<input type="checkbox" name="editRoleId" value="'+roles[i].roleid+'" />'+roles[i].rolename+' &nbsp;&nbsp;&nbsp;&nbsp;';
							
						}
							
					}
					$("#updaterolecheckbox").html(rolehtml);
					
					//window.location.href="./page/success.jsp";
				}else{
				  alert(ret.msg);
				}
			},
			error:function(e){
				alert("e:"+e);
			}
		});
	}
	
	
	//TODO 修改方法
	function updateUserInfo(){
		var username= $("#username").val();
		var nickname= $("#nickname").val();
		var status= $("#status").val();
		var userId= $("#editUserId").val();
		var status=$('input:radio[name="editradio"]:checked').val();
		var roleArray = getCheckBoxValue("editRoleId");
		
		console.log("roleArray:"+roleArray);
		$.ajax({
			type:"post",
			url:"/sys/user/updatalist",
			data:{"nickname":nickname,"status":status,"userId":userId,"roleIds":roleArray.join(",")},
			dataType:"json",
			success:function(ret){
				if(ret.code==0){
					toastr.info("修改成功");
					$("#coloseModel").click();
					$('#tb_users').bootstrapTable('refresh');					
					//window.location.href="./page/success.jsp";
				}else{
				  alert(ret.msg);
				}
			},
			error:function(e){
				alert("e:"+e);
			}
		});
	}
	//TODO 删除方法
function DeleteByIds(id){
	$.ajax({
		type:"post",
		url:"sys/deleteUser",
		data:{"userId":id},
		dataType:"json",
		success:function(ret){
			if(ret.code==0){
				toastr.info("删除成功");
				$("#coloseModel").click();
				$('#tb_users').bootstrapTable('refresh');					
				//window.location.href="./page/success.jsp";
			}else{
			  alert(ret.msg);
			}
		},
		error:function(e){
			alert("e:"+e);
		}
	});
}

//清空弹框值   + 遍历checkbox
function clearDate(){
	$("#addusername").val("");
	$("#addusername").val("");
	$("#addstatus").val(1);
	$("#addeptId").val(0);
	$("#adddeptName").val("");
	
	$.ajax({
		type:"post",
		url:"/sys/queryRoleByUserId",
		data:{},
		dataType:"json",
		success:function(ret){
			var rolelist = ret.data;
			var rolehtml='';
			for(var i=0;i<rolelist.length;i++){
				rolehtml+='<input type="checkbox" name="addRoleId" value="'+rolelist[i].roleid+'" />'+rolelist[i].rolename+' &nbsp;&nbsp;&nbsp;&nbsp;';
			}
			$("#rolecheckbox").html(rolehtml);
			
		},
		error:function(e){
			console.log("e:"+e);
		}
	});	
}

//获取CheckBox.value
function getCheckBoxValue(name){
	 var arr = new Array();                
     var items = document.getElementsByName(name);                 
     for (i = 0; i < items.length; i++) {                    
         if (items[i].checked) {                        
             arr.push(items[i].value);                    
         }                
     }
     return arr;
}

   //TODO  新增方法
function insertUser(){
	var addusername= $("#addusername").val();
	if(!addusername){
		$("#addusernamemsg").html("<font color='red'>用户名不能为空</font>");
		return;
	}
	var addnickname= $("#addnickname").val();
	var addstatus= $("#addstatus").val();
	var addstatus=$('input:radio[name="addradio"]:checked').val();
	var addeptid = $("#addeptId").val();
	var roleArray = getCheckBoxValue("addRoleId");
	$.ajax({
		type:"post",
		url:"/sys/insertUserByUsername",
		data:{"username":addusername,"nickname":addnickname,
			"status":addstatus,"deptId":addeptid,"roleIds":roleArray.join(",")},
		dataType:"json",
		success:function(ret){
			if(ret.code==0){
				toastr.info("新增成功");
				$("#addcoloseModel").click();
				$('#tb_users').bootstrapTable('refresh');
				//window.location.href="./page/success.jsp";
			}else{
			  alert(ret.msg);
			}
		},
		error:function(e){
			console.log("e:"+e);
		}
	});
}

function showDeptZtree(){
	
	layer.open({
		  type: 1,
		  skin: 'layui-layer-demo', //样式类名
		  area: ['250px', '300px'], //宽高
		  closeBtn: 1, //不显示关闭按钮
		  anim: 2,
		  shadeClose: false, //开启遮罩关闭
		  btn: ['确定'],
		  content:'<ul id="deptztree" class="ztree"></ul>',
		  
	});
	loadDeptData();
	
} 

function loadDeptData(){
	
	    var setting = {
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				onClick: zTreeOnClick
			}
		};
		
	    $.ajax({
	    	url:"/sys/queryDeptByUserId",
	    	type:"post",
	    	dataType:"json",
	    	data:{},
			success:function(ret){
				var tempdata = ret.data;
				$.fn.zTree.init($("#deptztree"), setting, tempdata);
			},
			error:function(e){
				alert("e:"+e);
			}
	    	
	    	
	    });		
}

function zTreeOnClick(event, treeId, treeNode) {
   //alert(treeNode.id + ",treeId " +treeId+ "======="+treeNode.name);
   $("#addeptId").val(treeNode.id);
   $("#adddeptName").val(treeNode.name);
    
    
}
</script>
</html>
